package hzmg.akkacloud.server.remote.worker;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.hzmg.akkacloud.common.request.WorkerHeartbeat;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 管理 worker 集群信息
 *
 * @author zbw
 * @since 2022/7/17
 */
@Slf4j
public class WorkerClusterManagerService {

    // 存储Worker健康信息，appId -> ClusterStatusHolder
    private static final Map<Long, ClusterStatusHolder> appId2ClusterStatus = Maps.newConcurrentMap();
    // 不想重构了为了实现某个需求而妥协的产物 T_T
    private static final Map<String, ClusterStatusHolder> appName2ClusterStatus = Maps.newConcurrentMap();
    /**
     * 更新状态
     *
     * @param heartbeat Worker的心跳包
     */
    public static void updateStatus(WorkerHeartbeat heartbeat) {
        Long appId = heartbeat.getAppId();
        String appName = heartbeat.getAppName();
        ClusterStatusHolder clusterStatusHolder = appId2ClusterStatus.computeIfAbsent(appId, ignore -> new ClusterStatusHolder(appName));
        clusterStatusHolder.updateStatus(heartbeat);
        //妥协 T_T 偷懒
        ClusterStatusHolder clusterStatusHolder2 = appName2ClusterStatus.computeIfAbsent(appName, ignore -> new ClusterStatusHolder(appName));
        clusterStatusHolder2.updateStatus(heartbeat);
    }

    /**
     * 清理不需要的worker信息
     *
     * @param usingAppIds 需要维护的appId，其余的数据将被删除
     */
    public static void clean(List<Long> usingAppIds) {
        Set<Long> keys = Sets.newHashSet(usingAppIds);
        appId2ClusterStatus.entrySet().removeIf(entry -> !keys.contains(entry.getKey()));
    }


    /**
     * 清理缓存信息，防止 OOM
     */
    public static void cleanUp() {
        appId2ClusterStatus.values().forEach(ClusterStatusHolder::release);
    }

    protected static Map<Long, ClusterStatusHolder> getAppId2ClusterStatus() {
        return appId2ClusterStatus;
    }
    protected static Map<String, ClusterStatusHolder> getAppName2ClusterStatus() {
        return appName2ClusterStatus;
    }
}
